cphsoc_stata_generate_dofile <- function(var_labels,var_types,data_path,var_names,val_labels,missings,dta_replace,stata_dta_path,char_var_max_lengths)
{
  trim <- function(x) {
    gsub('"',"'",gsub('\\s+$|^\\s+','',x))
  }

  # initialize empty char-vector of the correct length
  col_type <- character(length(var_types))
  
  # add 'str' in front of length number (i.e.: str50)
  col_type[which('character'==var_types)] <- ' str'
  col_type <- paste(col_type,char_var_max_lengths,sep='')
  
  # concatenate to one string, create the 'infile'-command
  column_def_str <- paste(paste(col_type,enc2utf8(var_names)),collapse='')
  column_def_str <- paste('infile ',column_def_str,' using "',data_path,'"\n\n',sep='')

  # loop through variables
  # initialize output (as list b/c it's more memory efficient)
  vlout <- list()
  vlout[[length(vlout)+1]] <- column_def_str
  
  for(i in 1:length(var_names))
  {
    # stata code to assign variable label
    vlout[[length(vlout)+1]] <- paste('label variable ',var_names[i],' "',gsub('"',"'",var_labels[i]),'"\n',sep="")
    
    ####################################################
    # value labels
    ####################################################
    # type is one of 'none'. 'one','two','three',''
    if(!is.null(val_labels[[i]]))
    {
      # make format name
      fmt_name <- paste(var_names[i],'_fmt',sep='')
      
      v <- val_labels[[i]]
      if(var_types[i]=='character')
      {
        ix <- sort(v,index.return=TRUE)$ix
        vallab_str <- paste(paste('*  "',trim(v[ix]),' = ',trim(names(v)[ix]),'"',sep=''),collapse='\n',sep='')
#         var_lab_str <- paste(var_lab_str,vallab_str,'\n',sep='')
        vlout[[length(vlout)+1]] <- paste(vallab_str,'\n',sep='')
      }
      else
      {
        ix <- sort(as.numeric(v),index.return=TRUE)$ix
        vlout[[length(vlout)+1]] <- paste(paste('label define ',fmt_name,' ',v[ix],' "',trim(names(v)[ix]),'", modify',sep=''),collapse='\n',sep='')
        
        # get value labels and values
        tmp_vlabs <- sort(val_labels[[i]])
        vlabs <- names(tmp_vlabs)
        vvals <- as.numeric(tmp_vlabs)
        ### missing values
        if(!is.null(missings[[i]]))
        {
          ret_str     <- cphsoc_spss_to_stata_misval(fmt_name,vlabs,vvals,missings[[i]],var_names[i])
          mis_str <- paste('\n*** Missing values ***\n',ret_str$val2mis_str,ret_str$vlabs_str,sep='')
        }
        else
        {
          mis_str <- ""
        }
        vlout[[length(vlout)+1]] <- mis_str
      }
    }
    vlout[[length(vlout)+1]] <- '\n'
  }
  
  if(dta_replace)
  {
    vlout[[length(vlout)+1]] <- paste('save "',stata_dta_path,'",orphans replace\n',sep='')
  }
  else
  {
    vlout[[length(vlout)+1]] <- paste('save "',stata_dta_path,'",orphans\n',sep='')
  }
  
  # write stata do file
  var_lab_str <- paste(vlout,collapse='')
  return(var_lab_str)
}